
app.factory("imageService", ["$q", "$timeout", function ($q, $timeout) {
    function ImageService() {
    }

    ImageService.prototype.create = function (src) {
        var deferred = $q.defer();
        var image = new Image();
        image.onloadprogress = function (e) {
            //console.log("onloadprogress", e);
            var value = e.loaded / e.total;
            deferred.notify(value);
        };
        image.onload = function () {
            deferred.resolve(image);
        };
        image.src = src;
        return deferred.promise;
    };

    ImageService.prototype.toDataURL = function (src) {
        var self = this;
        return self.create(src).then(function (image) {
            return self.imageToDataURL(image);
        })
    };

    ImageService.prototype.imageToDataURL = function (image) {
        return $timeout(function () {
            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            canvas.width = image.width;
            canvas.height = image.height;
            context.drawImage(image, 0, 0);
            return canvas.toDataURL("image/png");
        });

    };

    return new ImageService();
} ]);